<template>
  <div class="container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <!-- 搜索区域 -->
        <el-form class="demo-form-inline " label-width="80px">
          <el-form-item label="关键字" class="search-regional">
            <el-input
              placeholder="根据文章标题搜索"
              style="width:200px"
              size="small"
              v-model.trim="keyword"
            ></el-input>
          </el-form-item>
          <el-form-item label="状态" class="search-regional">
            <el-select
              placeholder="请选择"
              size="small"
              class="option"
              v-model="state"
            >
              <el-option label="启用" value="1"></el-option>
              <el-option label="禁用" value="0"></el-option>
            </el-select>
            <el-button size="small" @click="onClear">清除</el-button>
            <el-button size="small" type="primary" @click="getList"
              >搜索</el-button
            >
          </el-form-item>
        </el-form>
        <!-- 添加按钮 -->
        <el-button
          class="addskills"
          type="success"
          size="small"
          icon="el-icon-edit"
          @click="changeItemArticles(true)"
          >新增技巧</el-button
        >

        <!-- 提示条 -->
        <el-alert
          :title="` 数据一共 ${this.total} 条`"
          :closable="false"
          show-icon
        >
        </el-alert>

        <!-- 列表区域 -->
        <el-table :data="tableData" style="width: 100%">
          <el-table-column type="index" label="序号" width="80">
          </el-table-column>
          <el-table-column label="文章标题" width="400">
            <template slot-scope="scope">
              <span>{{ scope.row.title }}</span>
            </template>
          </el-table-column>
          <el-table-column label="阅读数">
            <template slot-scope="scope">
              <span>{{ scope.row.visits }}</span>
            </template>
          </el-table-column>
          <el-table-column label="录入人">
            <template slot-scope="scope">
              <span>{{ scope.row.username }}</span>
            </template>
          </el-table-column>
          <el-table-column label="录入时间">
            <template slot-scope="scope">
              <span>{{ scope.row.createTime | parseTimeByString }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="" label="状态" width="100">
            <template slot-scope="scope">
              <span v-if="scope.row.state == 1">已启用</span>
              <span v-else>已禁用</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="180">
            <template slot-scope="scope">
              <!-- 预览 -->
              <el-button
                type="text"
                size="medium"
                @click="PreviewIetm(scope.row)"
                >预览</el-button
              >

              <!-- 启用、禁用 -->
              <el-button
                type="text"
                size="medium"
                @click="stateChange(scope.row)"
              >
                {{ scope.row.state == 1 ? '禁用' : '启用' }}
              </el-button>

              <!-- 修改-->
              <el-button
                type="text"
                size="medium"
                @click="changeItemArticles(false, scope.row)"
                :disabled="scope.row.state === 1"
                >修改
              </el-button>

              <!-- 删除-->
              <el-button
                type="text"
                size="medium"
                @click="removeItem(scope.row.id)"
                :disabled="scope.row.state === 1"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :total="total"
            background
            :current-page="page"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="10"
            layout="prev, pager, next, sizes, jumper"
          >
          </el-pagination>
        </div>
      </div>
    </el-card>

    <!-- 预览功能 -->
    <el-dialog
      title="预览文章"
      :visible.sync="Preview"
      width="42%"
      :data="Previewdata"
    >
      <h2>{{ Previewdata.title }}</h2>
      <span> {{ Previewdata.createTime | parseTimeByString }} </span>
      <span style="margin: 0 10px"> {{ Previewdata.username }} </span>
      <span class="el-icon-view"> {{ Previewdata.visits }} </span>
      <div class="previewText" v-html="Previewdata.articleBody"></div>
    </el-dialog>

    <!-- 修改 、添加功能弹框 -->
    <el-dialog
      :title="changeTitle"
      :visible.sync="changeItem"
      width="42%"
      @close="handleClose"
    >
      <el-form
        label-width="100px"
        :model="changeItemdata"
        ref="changeItemdataRef"
        :rules="changeItemdataRules"
      >
        <el-form-item label="文章标题：" prop="title">
          <el-input
            type="text"
            autocomplete="off"
            v-model.trim="changeItemdata.title"
            placeholder="请输入文章标题"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="文章内容："
          class="quill_editorBox"
          prop="articleBody"
        >
          <!-- 富文本编辑器 -->
          <quill-editor
            :options="editorOption"
            class="quill_editor"
            v-model.trim="changeItemdata.articleBody"
          >
          </quill-editor>
        </el-form-item>
        <el-form-item label="视频地址：" prop="videoURL">
          <el-input
            placeholder="请输入视频地址"
            v-model.trim="changeItemdata.videoURL"
          ></el-input>
        </el-form-item>
        <el-form-item class="submissions">
          <el-button @click="changeItem = false">取消</el-button>
          <el-button type="primary" @click="onSubmit">确认</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
// 导入 文章列表 、文章添加 、文章修改 、文章删除 、文章状态 接口
import { list, add, update, remove, changeState } from '@/api/hmmm/articles'
export default {
  name: 'Articles',
  data () {
    return {
      keyword: null, // 关键字
      state: null, // 状态
      page: 1, // 分页默认
      pagesize: 10, // 每页条数
      tableData: [], // 列表数据
      total: 0, // 获取总条数
      alertText: '', // 提示数据总条数
      Preview: false, // 预览弹框
      Previewdata: [], // 预览框数据
      changeItem: false, // 修改文章弹框
      changeItemdata: {}, // 修改文章弹框数据
      // 富文本
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序列表，无序列表
            ['blockquote', 'code-block'], // 引用，代码块
            ['image', 'link'] // 图片 链接
          ]
        },
        placeholder: '请输入文章内容'
      },
      // 富文本
      changeTitle: '新增文章', // 增加修改弹出框标题
      changeItemdataRules: {
        title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
        articleBody: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ]
      }
    }
  },
  mounted () {
    // 列表数据
    this.getList()
  },
  methods: {
    // 清除，搜索点击事件
    onClear () {
      this.keyword = null
      this.state = null
      this.getList()
    },
    // 获取列表数据
    async getList () {
      try {
        const { data: res } = await list({
          page: this.page, // 当前页数
          pagesize: this.pagesize, // 页尺寸
          keyword: this.keyword, // 关键字
          state: this.state // 状态
        })
        this.tableData = res.items
        // 获取总条数
        this.total = res.counts
      } catch (err) {
        this.$message.error('获取数据列表失败！')
      }
    },
    // 预览
    PreviewIetm (row) {
      this.Preview = true
      this.Previewdata = row
    },
    // 启用、禁用
    async stateChange (row) {
      row.state = row.state === 1 ? 0 : 1
      try {
        await changeState({
          id: row.id,
          state: row.state
        })
        this.$message.success('状态变更成功！')
      } catch (err) {
        this.$message.error('更新状态失败！')
      }
    },
    // 修改 ,添加功能
    changeItemArticles (flag, row) {
      this.changeItem = true
      this.flag = flag
      if (flag) {
        // 添加
      } else {
        // 修改
        this.changeTitle = '修改文章'
        this.changeItemdata = JSON.parse(JSON.stringify(row))
      }
    },
    // 修改 、添加提交
    onSubmit () {
      this.$refs.changeItemdataRef.validate(async valid => {
        if (!valid) {
          return this.$message({
            message: '标题或内容不能为空！',
            center: true,
            type: 'error'
          })
        }
        // this.$message.error('标题或内容不能为空！')
        if (this.flag) {
          // 添加文章
          try {
            await add({
              title: this.changeItemdata.title,
              articleBody: this.changeItemdata.articleBody
            })
            this.getList()
            this.$message.success('添加文章成功！')
          } catch (err) {
            this.$message.error('添加文章失败！')
          }
          this.changeItem = false
        } else {
          // 修改文章
          try {
            await update({
              id: this.changeItemdata.id,
              title: this.changeItemdata.title,
              articleBody: this.changeItemdata.articleBody
            })
            this.getList()
            this.$message.success('修改文章成功！')
          } catch (err) {
            this.$message.error('修改文章失败！')
          }
          this.changeItem = false
        }
      })
    },
    // 删除功能
    async removeItem (id) {
      const confirm = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirm !== 'confirm') return
      try {
        await remove({ id })
        if (this.tableData.length === 1) {
          this.page = this.page === 1 ? 1 : this.page - 1
        }
        this.$message.success({
          message: '已删除一条文章！',
          center: true
        })
        this.getList()
      } catch (err) {
        this.$message.error('删除失败')
      }
    },
    // 监听修改,添加功能弹框关闭事件
    handleClose () {
      this.$refs.changeItemdataRef.resetFields()
    },
    // 监听分页
    handleSizeChange (newSize) {
      this.pagesize = newSize
      this.getList()
    },
    handleCurrentChange (newPage) {
      this.page = newPage
      this.getList()
    }
  }
}
</script>

<style scoped lang="less">
.container {
  padding: 10px;
  .search-regional {
    float: left;
  }
  .el-option {
    float: left;
  }
  .option {
    margin-right: 10px;
  }
  .addskills {
    float: right;
  }
  .el-alert {
    margin-bottom: 15px;
  }
  .el-pagination {
    float: right;
    margin-top: 10px;
  }
  .submissions {
    display: flex;
    justify-content: flex-end;
    margin-top: 60px;
  }
  .previewText {
    background-color: #f5f5f5;
    margin-top: 10px;
    padding: 15px;
    border-top: 1px dashed #ccc;
  }
  .quill_editorBox {
    height: 250px;
    /deep/ .el-form-item__content {
      height: 252px;
    }
  }
  .quill_editor {
    height: 200px;
  }
}
</style>
